﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;
using System.ComponentModel;
using System.Reflection;
using System.Web.Configuration;
using VBBLL;
using VBModel;

namespace VenueManage
{
    /// <summary>
    /// Booking_confirm 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务，请取消注释以下行。 
    [System.Web.Script.Services.ScriptService]
    public class Booking_confirm : System.Web.Services.WebService
    {

        [WebMethod]
        public string AddAdmin(string adminName, string adminLevel)
        {
            try
            {
                MTR_bas_Admin ma = new MTR_bas_Admin();
                ma.adminName = adminName;
                ma.adminLevel = Convert.ToInt32(adminLevel);
                new BaseRepositoryBLL<MTR_bas_Admin>().AddEntities(ma);
                return "添加成功";
            }
            catch (Exception ex)
            {
                Worker.writeErrorMessage("0", ex, "ADDAdmin");
                return ex.Message;
            }
        }

        [WebMethod(EnableSession = true)]
        public string CheckUser(string userName, string pwd)
        {
            string AD_AccountNo = userName;
            string AD_Password = pwd;
            //在这里校验AD用户及密码
            string domainName = "GWKF";
            string adPath = "LDAP://" + domainName;
            
            if (checkAD(adPath, domainName, AD_AccountNo, AD_Password))
            {
                Session["userName"] = userName;
                return "Succsee";
            }
            else return "error";
        }

        [WebMethod]
        public int CheckUserName(string userName)
        {
            string cString = WebConfigurationManager.ConnectionStrings["WorkFlowConnectionString"].ConnectionString;
            string strSQL =string.Format(@"select 1 from [WorkFlow].[dbo].[RUC_Users] where SamAccountName='{0}' and IfDelete=0",userName);
            DataTable dt = Worker.GetDataSet(strSQL, cString).Tables[0];
            return dt.Rows.Count;
        }

        [WebMethod]
        private bool checkAD(string adPath, string domainName, string AD_AccountNo, string AD_Password)
        {
            LdapAuthentication adAuth = new LdapAuthentication(adPath);
            //自己寫的類別檔。
            try
            {
                return adAuth.IsAuthenticated(domainName, AD_AccountNo, AD_Password);
            }
            catch (Exception ex)
            {
                Worker.writeErrorMessage("0", ex, "checkAD");
                return false;
            }
            
        }


        [WebMethod]
        public string Booking(string participants, string meetingTheme, string meetingAbstract, string mtrAdd, string mtrName, string specialRequestFirst,
                string specialRequestSecond, string startDate, string startTime, string endDate, string endTime)  //, string[] weekdays
        {
            int mtrNo = Convert.ToInt32(mtrName.Remove(mtrName.Length - 1, 1));//会议室名称改成会议室编号
            //字符串转换成时间

            DateTime st = DateTime.ParseExact(startDate + " " + startTime, "yyyy-MM-dd-HH-mm", null);
            DateTime et = DateTime.ParseExact(endDate + " " + endTime, "yyyy-MM-dd-HH-mm", null);
            //if(startDate==endDate && ){}
            string dateDiff = null;
            TimeSpan ts1 = new TimeSpan(st.Ticks);
            TimeSpan ts2 = new TimeSpan(et.Ticks);
            TimeSpan ts = ts1.Subtract(ts2).Duration();
            //显示时间  
            dateDiff = ts.Days.ToString() + "天"
                    + ts.Hours.ToString() + "小时"
                    + ts.Minutes.ToString() + "分钟"
                    + ts.Seconds.ToString() + "秒";
            if (ts.Days < 1 && ts.Hours < 4)
            {
                //满足条件
                SelfBookingSuccess(participants, meetingTheme, meetingAbstract, mtrAdd, mtrNo, specialRequestFirst,
                specialRequestSecond, st, et);//, weekdays
            }
            return "OK";
        }
        //条件满足，完成自助预定
        public static void SelfBookingSuccess(string participants, string meetingTheme, string meetingAbstract, string mtrAdd, int mtrNo, string specialRequestFirst,
                string specialRequestSecond, DateTime st, DateTime et)//, string[] weekdays
        {
            MTR_bas_BookingManage mtrBM = new MTR_bas_BookingManage();
            mtrBM.bookingType = "自助";
            mtrBM.Meetingroom = mtrNo;
            mtrBM.bookingPerson = "";
            mtrBM.bookingTime = st;
            //mtrBM.endTime = et;
            mtrBM.meetingTheme = meetingTheme;
            mtrBM.participants = participants;
            mtrBM.meetingAbstract = meetingAbstract;
            mtrBM.specialRequestFirst = specialRequestFirst;
            mtrBM.specialRequestSecond = specialRequestSecond;
            mtrBM.bookingState = 2;
            new BaseRepositoryBLL<MTR_bas_BookingManage>().AddEntities(mtrBM);
           
        }

        [WebMethod(EnableSession = true)]
        public string CancelBooking(string bookingId, string reason, string passWord)
        {
            var mtr = new VenueBookingTestEntities(); // new meetingroomManagementEntities();
            var cls = new BaseRepositoryBLL<MTR_bas_BookingManage>().LoadEntities(p => p.bookingID.Equals(bookingId)).FirstOrDefault();
                //(from bm in mtr.MTR_bas_BookingManage join bs in mtr.MTR_bas_BookingSchedul 
                //       on bm.bookingID equals bs.planId
                //       where bm.bookingID == bookingId 
                //       select bm).SingleOrDefault<MTR_bas_BookingManage>();
            var clm = new BaseRepositoryBLL<MTR_bas_BookingSchedul>().LoadEntities(p => p.planId.Equals(bookingId)).FirstOrDefault();
                //(from bm in mtr.MTR_bas_BookingManage
                //       join bs in mtr.MTR_bas_BookingSchedul
                //           on bm.bookingID equals bs.planId
                //       where bm.bookingID == bookingId
                //       select bs).SingleOrDefault<MTR_bas_BookingSchedul>();
            var cmtr = new BaseRepositoryBLL<MTR_bas_Meetingroom>().LoadEntities(p => p.mtrId.Equals(cls.Meetingroom)).FirstOrDefault();
                //(from bm in mtr.MTR_bas_BookingManage
                //        join venue in mtr.MTR_bas_Meetingroom
                //        on bm.Meetingroom equals venue.mtrId
                //        where bm.bookingID == bookingId
                //        select venue).SingleOrDefault<MTR_bas_Meetingroom>();
            
            DateTime st = DateTime.Parse(clm.meetingStartDate.Value.ToLongDateString() + clm.startTime);
            DateTime et = DateTime.Parse(clm.meetingEndDate.Value.ToLongDateString() + clm.endTime);
            string mtrAdd = cmtr.mtrAddress + cmtr.mtrAddress1 + " " + cmtr.mtrName;
            string meetingTheme = "取消" + cls.meetingTheme;
            string meetingAbstract = cls.meetingAbstract;
            string userName = cls.bookingPerson;
            string participate = cls.participants;
            string ccs = "";// cls.undefine3;

            string[] attendees = participate.Split(';');
            string[] cc = ccs.Split(';');
            if (cls.bookingState == 1 || cls.bookingState == 2)
            {
                emailSrv e = new emailSrv();
                e.SendMeetingRequest(st, et, mtrAdd, meetingTheme, reason, attendees, cc,
                              bookingId, true, userName, userName + "@kaifa.cn", false, passWord);
            }
            cls.bookingState = 4;//状态改为4 意味着取消预订
            cls.cancelPerson = Session["userName"].ToString();//取消的人
            cls.cancelReason = reason;//取消的原因
            cls.cancelTime = DateTime.Now;
            //mtr.SaveChanges();
            new BaseRepositoryBLL<MTR_bas_BookingManage>().UpdateEntities(cls);
            return "取消成功";
        }

        [WebMethod]
        public Object ShowEveInfor(string bookingId)
        {
            EventInformation ei = new EventInformation();
            var mtr = new VenueBookingTestEntities(); //new meetingroomManagementEntities();
            var query = (from bm in mtr.MTR_bas_BookingManage
                         from bs in mtr.MTR_bas_BookingSchedul
                         from m in mtr.MTR_bas_Meetingroom
                         where bm.Meetingroom == m.mtrId && bm.bookingID == bs.planId &&
                         bm.bookingID == bookingId //&& resMtr.mtrId == m.mtrId
                         select new //EventInformation
                         {
                             participants = bm.participants,
                             meetingTheme = bm.meetingTheme,
                             MeetingRoom = bm.Meetingroom,
                             bookingPerson = bm.bookingPerson,
                             mtrAddress = m.mtrAddress,
                             mtrAddress1 = m.mtrAddress1,
                             mtrName = m.mtrName,
                             TelePhoneNumber = bs.undefine2,
                             mtrCapacity =m.mtrCapacity,
                             specialRequestFirst = bm.specialRequestFirst,
                             specialRequestSecond = bm.specialRequestSecond,
                             meetingStartDate = bs.meetingStartDate,
                             startTime = bs.startTime,
                             meetingEndDate = bs.meetingEndDate,
                             endTime = bs.endTime,
                             meetingAbstract = bm.meetingAbstract,
                             isPeriodic = bs.isPeriodic,
                             Monday = bs.Monday,
                             Tuesday = bs.Tuesday,
                             Wednesday = bs.Wednesday,
                             Thursday = bs.Thursday,
                             Friday = bs.Friday,
                             Sunday = bs.Sunday,
                             Saturday = bs.Saturday
                         }).SingleOrDefault();
            if (query == null) {
                return query;
            }
            List<string> resList = new List<string>();
            var List = (from m in mtr.MTR_bas_Meetingroom
                           from resMtr in mtr.MTR_bas_MeetingroomResources
                           from res in mtr.MTR_bas_Resources
                           where resMtr.mtrId == query.MeetingRoom && resMtr.resId == res.resId
                               && res.del
                           select new
                           {
                               res.resName
                           }).Distinct().ToList();
            foreach (var res in List){
                resList.Add(res.resName.ToString());
            }
            RUC r = new RUC();
            List<RucOrganizationExtend> userOrg = r.GetOrgLayeringBySamAccountNames(query.bookingPerson);
            foreach (RucOrganizationExtend org in userOrg)
            {
                if (org.Organization.OrgTypeID == 1)
                {
                    ei.orgType1 = org.Organization.ABBR;
                }
                if (org.Organization.OrgTypeID == 3)
                {
                    ei.orgType3 = org.Organization.ABBR;
                }
            }
            ei.TelePhoneNumber = query.TelePhoneNumber;
            ei.mtrResName = resList;
            ei.participants = query.participants;
            ei.meetingTheme = query.meetingTheme;
            ei.MeetingRoom = query.MeetingRoom;
            ei.bookingPerson = query.bookingPerson;
            ei.mtrAddress = query.mtrAddress;
            ei.mtrAddress1 = query.mtrAddress1;
            ei.mtrName = query.mtrName;
            ei.mtrCapacity = Convert.ToInt32(query.mtrCapacity);
            ei.specialRequestFirst = query.specialRequestFirst;
            ei.specialRequestSecond = query.specialRequestSecond;
            ei.meetingStartDate = query.meetingStartDate;
            ei.startTime = query.startTime;
            ei.meetingEndDate = query.meetingEndDate;
            ei.endTime = query.endTime;
            ei.isPeriodic = query.isPeriodic;
            ei.Monday = query.Monday;
            ei.Tuesday = query.Tuesday;
            ei.Wednesday = query.Wednesday;
            ei.Thursday = query.Thursday;
            ei.Friday = query.Friday;
            ei.Saturday = query.Saturday;
            ei.Sunday = query.Sunday;
            return ei;
        }

    }
}
